package com.woniuxy.buyer.controller;

import com.woniuxy.buyer.service.AuthService;
import com.woniuxy.common.entity.User;
import com.woniuxy.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        if (username == null || password == null) {
            return Result.badRequest("用户名和密码不能为空");
        }

        try {
            String token = authService.login(username, password);
            User user = authService.getUserByToken(token);

            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);

            return Result.success("登录成功", data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestHeader("Authorization") String token) {
        User user = authService.getUserByToken(token);
        if (user == null) {
            return Result.unauthorized("无效的token");
        }
        return Result.success(user);
    }

    /**
     * 验证用户角色
     */
    @GetMapping("/validate")
    public Result<Map<String, Object>> validateRole(
            @RequestHeader("Authorization") String token,
            @RequestParam String expectedRole) {
        boolean valid = authService.validateUserRole(token, expectedRole);
        Map<String, Object> data = new HashMap<>();
        data.put("valid", valid);

        if (valid) {
            return Result.success("验证通过", data);
        } else {
            return Result.forbidden("角色验证失败", data);
        }
    }
}
